import { useEffect } from 'react'
import { useNavigate, useLocation } from 'react-router-dom'
import {
  MinusOutlined,
  FullscreenOutlined,
  CloseOutlined,
  UserOutlined,
} from '@ant-design/icons'
import { Image, Avatar } from 'antd'
// observer 是一个高阶组件函数，需要包裹一个组件，这样组件才会更新
import { observer } from 'mobx-react-lite'
import styles from './index.module.less'
import logoImg from '@/assets/image/drawingBed.png'
import { userInfoStore } from '@/store/store'
import { sourceUrl } from '@/config'

function Header() {
  // 最小化窗口
  const minWindow = () => (window as any).controlWindow.minWindow()
  // 切换最大化窗口
  const toggleMaxWindow = () => (window as any).controlWindow.maxWindow()
  // 关闭窗口
  const closeWindow = () => (window as any).controlWindow.closeWindow()

  const navigate = useNavigate()
  const location = useLocation()

  const { nickname, avatar } = userInfoStore

  useEffect(() => {
    userInfoStore.getUserInfo()

    userInfoStore.onLoginStatusChange((newStatus) => {
      if (newStatus && location.pathname === '/login') navigate('/home')
      if (newStatus && location.pathname === '/') navigate('/home')
    })
  }, [])

  return (
    <div className={styles.header}>
      {/* 左边控制窗口按钮 */}
      <div className={styles.controlBtns}>
        <div>
          <MinusOutlined
            title="最小化"
            style={{ fontSize: '12px' }}
            onClick={minWindow}
          />
        </div>
        <div>
          <FullscreenOutlined
            title="全屏"
            style={{ fontSize: '12px' }}
            onClick={toggleMaxWindow}
          />
        </div>
        <div>
          <CloseOutlined
            title="关闭"
            style={{ fontSize: '12px' }}
            onClick={closeWindow}
          />
        </div>
      </div>

      {/* 中间logo */}
      <div className={styles.logoImg}>
        <Image
          width={28}
          src={logoImg}
          preview={false}
          onClick={() => navigate('/home')}
        />
      </div>

      {/* 右边昵称 */}
      <div className={styles.username} onClick={() => navigate('/user')}>
        <Avatar
          size={26}
          icon={<UserOutlined />}
          shape="square"
          src={sourceUrl + avatar}
        />
        &nbsp;{nickname}
      </div>
    </div>
  )
}

export default observer(Header)
